<template>
    <div class="doc-table">
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item><i class="el-icon-menu"></i> 内容管理</el-breadcrumb-item>
                <el-breadcrumb-item>文档管理</el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="handle-box">
            <el-button type="primary" size="mini" icon="" @click="addDocument">添加文章</el-button>
            <el-button type="primary" size="mini" icon="" @click="delSelected">批量删除</el-button>
            <el-button type="primary" size="mini" icon="" @click="passSelected" v-if="isAdmin">批量审核</el-button>
            <div class="fr">
                <el-cascader size="mini"
                             placeholder="请选择栏目"
                             expand-trigger="hover"
                             v-model="arttype"
                             :options="arttypeOption"
                             :props="arttypeProps"
                             @change="handleChange">
                </el-cascader>
                <el-select class="handle-select" size="mini" v-model="audit" placeholder="请选择">
                    <el-option v-for="item in auditFilter"
                               :key="item.value"
                               :label="item.label"
                               :value="item.value">
                    </el-option>
                </el-select>
                <el-input placeholder="标题" size="mini" class="handle-input" v-model="keyword"></el-input>
                <el-button type="primary" size="mini" icon="el-icon-search" @click="search()">查询</el-button>
            </div>
        </div>

        <el-table @selection-change="selsChange"
                  size="mini"
                  :data="tableData"
                  border
                  style="width: 100%">
            <el-table-column type="selection"
                             width="55">
            </el-table-column>
            <el-table-column :show-overflow-tooltip="true"
                             prop="arttitle"
                             label="标题"
                             min-width="320">
            </el-table-column>
            <el-table-column prop="delivertime"
                             label="发布时间"
                             width="160">
                <template slot-scope="scope">
                    <span>{{scope.row.delivertime?$moment(scope.row.delivertime).format('YYYY-MM-DD HH:mm:ss'):''}}</span>
                </template>
            </el-table-column>
            <el-table-column align="center"
                             prop="arttypename"
                             label="栏目"
                             width="140">
            </el-table-column>
            <el-table-column align="center"
                             prop="deliver"
                             label="发布状态"
                             width="80">
                <template slot-scope="scope">
                    <span close-transition v-if="scope.row.deliver==0">暂存</span>
                    <span close-transition v-else-if="scope.row.deliver==1">发布</span>
                </template>
            </el-table-column>
            <el-table-column align="center"
                             prop="audit"
                             label="审核状态"
                             width="80">
                <template slot-scope="scope">
                    <span close-transition v-if="scope.row.audit==0">待审核</span>
                    <span close-transition v-else-if="scope.row.audit==1">已审核</span>
                </template>
            </el-table-column>
            <el-table-column align="center"
                             prop="showflag"
                             label="显示"
                             width="80">
                <template slot-scope="scope">
                    <span close-transition v-if="scope.row.showflag==0">
                        <i class="el-icon-circle-close" style="color:#F56C6C;"></i>
                    </span>
                    <span close-transition v-else-if="scope.row.showflag==1">
                        <i class="el-icon-circle-check" style="color:#67C23A;"></i>
                    </span>
                </template>
            </el-table-column>
            <el-table-column align="center"
                             prop="readcount"
                             label="浏览次数"
                             width="100">
            </el-table-column>
            <el-table-column align="center"
                             prop="source"
                             label="来源"
                             width="100">
            </el-table-column>
            <el-table-column :show-overflow-tooltip="true"
                             align="center"
                             prop="author"
                             label="作者"
                             width="160">
            </el-table-column>
            <el-table-column fixed="right"
                             label="操作"
                             width="280">
                <template slot-scope="scope">
                    <el-button @click="editDocument(scope.$index, scope.row)" size="mini">编辑</el-button>
                    <el-button @click="targetTo(scope.$index, scope.row)" size="mini">跳转到文章</el-button>
                    <el-button @click="deleteRow(scope.row.artid)" type="danger" size="mini">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <!--分页-->
        <div class="pagination" style="float: left">
            <el-pagination small
                           @current-change="handleCurrentChange" background
                           layout="total, prev, pager, next, jumper"
                           :current-page="cur_page"
                           :total="totalCount">
            </el-pagination>
        </div>
    </div>
</template>


<script>

  export default {
    data: function () {
      return {
        cur_page: 1,
        pagerow: 10,
        totalCount: 1,
        tableData: [],
        selsData: [],
        isAdmin: false,
        username: '',
        deliver: '', //发布和暂存状态
        keyword: '',
        auditFilter: [{
          value: '',
          label: '全部状态'
        }, {
          value: '0',
          label: '待审核'
        }, {
          value: '1',
          label: '已审核'
        }],
        audit: '', //审核状态
        arttypeProps: {
          value: "catid",
          label: "catname",
          children: "children"
        },
        arttypeOption: [],
        arttype: [''],
        arttypename: []
      }
    },
    methods: {
      //查询
      search() {
        this.cur_page = 1;
        this.findArticle();
      },
      //批量删除
      delSelected() {
        let self = this;
        if (self.selsData.length == 0) {
          self.$message.error('当前没有选中文章!!!');
        } else {
          self.$confirm("确定删除所选文章吗?", "提示", {type: 'warning'})
            .then(() => {
              var idArr = self.selsData.map(item => item.artid)
              self.$axios.post('/art/delmultiple', {artid: idArr.join(',')})
                .then((res) => {
                  if (res.data.code == 0) {
                    self.$message.info(res.data.message);
                  } else {
                    self.$message.info(res.data.message);
                  }
                }).catch(err => {
                self.$message.error('请求服务器失败，请稍后再试！');
              })
              self.findArticle()
            }).catch(() => {
            self.$message.info('已取消批量删除操作!');
          })
        }
      },
      //批量审核
      passSelected() {
        var self = this;
        if (self.selsData.length == 0) {
          self.$message.error('当前没有选中文章!!!');
        } else {
          self.$confirm("确定审核通过所选文章吗?", "提示", {type: 'warning'})
            .then(() => {
              var idArr = self.selsData.map(item => item.artid)
              self.$axios.post('/art/pass', {artid: idArr.join(',')})
                .then((res) => {
                  if (res.data.code == 0) {
                    self.$message.info(res.data.message);
                  } else {
                    self.$message.info(res.data.message);
                  }
                }).catch(err => {
                self.$message.error('请求服务器失败，请稍后再试！');
              })
              self.findArticle()
            }).catch(() => {
            self.$message.info('已取消批量审核通过操作!');
          })
        }
      },
      addDocument() {
        this.$router.push({path: '/document_add'});
      },
      editDocument(index, row) {
        this.$router.push({path: '/document_edit', query: {id: row.artid}});
      },
      //TODO 地址动态设置
      targetTo(index, row) {
        window.open("http://localhost:6108/details/" + row.artid);
      },
      selsChange(val) {
        this.selsData = val;
      },
      //分页
      handleCurrentChange(val) {
        this.cur_page = val;
        this.findArticle()
      },
        handleChange(value) {
           // console.log(value);
        },
      //删除单条数据
      deleteRow(artid) {
        this.$confirm("确定删除此文章吗?", "提示", {type: 'warning'})
          .then(() => {
            this.$axios.post('/art/del', {artid: artid})
              .then((res) => {
                if (res.data.code == 0) {
                  this.$message.info(res.data.message);
                  this.getAllArticle()
                } else {
                  this.$message.error(res.data.message);
                }
              }).catch(err => {
              this.$message.error('请求服务器失败，请稍后再试！');
            })
          }).catch(() => {
          this.$message.info('已取消该删除操作!');
        })
      },
      //条件筛选
      findArticle() {
        var self = this
        var params = {
          page: self.cur_page,
          pagerow: self.pagerow,
          author: self.username,
          deliver: self.deliver,
          audit: self.audit,
          arttype: self.arttype[self.arttype.length - 1]
        }
        if (self.keyword !== '') {
          params.keyword = self.keyword
        }
        self.$axios.post('/art/getArticleList', params)
          .then(function (response) {
            if (response.data.code == 0) {
              var tplData = response.data.data

                self.tableData = tplData

              self.totalCount = response.data.rowcount
            } else {
              self.$message.error(response.data.message);
            }
          }).catch(() => {
          self.$message.error('请求服务器失败，请稍后再试！');
        })
      },
      //页面初始化
      async getAllArticle() {
        let self = this
          await self.getCategory();
        self.$axios.post('/art/getArticleList', {
          page: self.cur_page,
          pagerow: self.pagerow,
          author: self.username,
          deliver: self.deliver
        }).then(function (response) {
          if (response.data.code == 0) {
            var tplData = response.data.data

              tplData.forEach(function (item,index){
                  for(let catitem of self.arttypeOption)
                  {
                      if(item.arttype===catitem.catid)
                      {
                          item.arttypename=catitem.catname
                      }
                  }
              })
              self.tableData=tplData
            self.totalCount = response.data.rowcount
          } else {
            self.$message.error(response.data.message);
          }
        }).catch(() => {
          self.$message.error('请求服务器失败，请稍后再试！');
        })
      },
      //迭代删除空的指定属性
      deleteEmpty(arr, prop) {
        var self = this;
        for (var i = 0; i < arr.length; i++) {
          if (arr[i][prop].length == 0) {
            delete arr[i][prop]
          } else {
            self.deleteEmpty(arr[i][prop], prop)
          }
        }
      },
      //迭代树形数组转换成普通对象,id索引,name为值
      treeToObj(arr, newObj) {
        var self = this;
        for (var i = 0; i < arr.length; i++) {
          newObj[arr[i].catid] = arr[i].catname;
          if (arr[i].children && arr[i].children.length > 0) {
            self.treeToObj(arr[i].children, newObj)
          }
        }
        return newObj;
      },
        test(){
          return 'hello world'
        },
      async getCategory() {
        var self = this
        return self.$axios.post('/cat/getcatlist', {parentid: 'ROOT'}).then(function (res) {
          if (res.data.code == 0) {
            var arr = res.data.data
            self.deleteEmpty(arr, 'children');
            self.arttypeOption = arr
            arr.unshift({catid: '', catname: '全部栏目'})
              self.treeToObj(arr, {})

          } else {
            self.$message.error(res.data.message);
          }
        }).catch((err) => {
          self.$message.error('获取文章栏目分类失败，请稍后再试！');
        })
      },
      getRoleInfo(fn) {
        let self = this
        self.$axios.post('/role/getroleinfo', {roleid: sessionStorage.getItem('utype')})
          .then(function (response) {
            if (response.data.code == 0) {

            } else {
              this.$message.error(response.data.message);
            }
          })
          .catch(function (error) {
            throw error;
            this.$message.error('请求网络失败，请稍后再试！');
          });

      }
    },
    created() {
        //TODO 优化代码
      //  this.getCategory();
        this.getAllArticle();

    }
  }
</script>

<style scoped>
    .handle-box {
        margin-bottom: 20px;
    }

    .fr {
        float: right;
    }

    .handle-select {
        width: 160px;
    }

    .handle-input {
        width: 160px;
        display: inline-block;
    }
</style>
